// Do not remove the include below
#include "tcpServer2.h"

#include <JeeLib.h>
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 4, 150);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(6789);

extern HardwareSerial Serial;

MilliTimer sendTimer;
MilliTimer sendTimer2;
byte sendSize;
char payload[] = "ABC 0123456789";
boolean needToSend = false;

void setEthernet() {
	if (needToSend) {

		//sen(3) LOW && ss(10) HIGH to disable ethernet
		digitalWrite(3, LOW);
		digitalWrite(10, HIGH);
		//digitalWrite(9, LOW);
	}

	if (!needToSend) {
		digitalWrite(3, HIGH);
		digitalWrite(10, LOW);
		//digitalWrite(9, HIGH);

	}

}

void setup() {

	rf12_initialize(1, RF12_433MHZ, 33);

	// start the Ethernet connection and the server:
	Ethernet.begin(mac, ip);
	server.begin();
	Serial.begin(115200);
	Serial.print("33");


	pinMode(3, OUTPUT);
	pinMode(10, OUTPUT);
	//pinMode(9, OUTPUT);

}

void loop() {

	// send out a new packet every 2 seconds
	if (sendTimer.poll(2000)) {
		needToSend = true;
	}
	if (needToSend) {
		setEthernet();
		rf12_recvDone();
		if (rf12_canSend) {

			// send as broadcast, payload will be encrypted
			rf12_sendStart(0, payload, sendSize + 4);
			Serial.print("  send ");
			Serial.println((int) sendSize);
			needToSend = false;
		}
		setEthernet();
		Serial.println("setOk ");
	}


	// listen for incoming clients
	EthernetClient client = server.available();
	if (client) {
		// an http request ends with a blank line
		boolean currentLineIsBlank = true;
		if (client.connected()) {
			String data = "";
			Serial.println("1___");
			while (client.available()) {
				char c = client.read();   //data
				data += c;
				//delay(10);
			//	Serial.print("f");
			}
			Serial.println("2___");
			if (data != "") {
				Serial.println(data);

				//Serial.println(data.charAt(2));
				//Serial.println(data.charAt(6));
				//digitalWrite(data.charAt(2), data.charAt(6));
				data = "";
			}

			}

		// give the web browser time to receive the data
		//delay(1);
		// close the connection:
		//client.stop();
		//Serial.println("stop");
	}
}
